import { AfterViewInit, Component, OnDestroy, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { FormGroup } from '@angular/forms';
import { deepClone, replaceAll } from '../../../utils/utils';
import { toNumber } from '@shared/apes/core/util/convert';
import { Events } from '@core/services/events/Events';
import { ActivatedRoute, Router } from '@angular/router';
import { FormService } from '@core/services/form.service';
import { ApesNgSelectComponent } from '@shared/apes-secondary-package/apes-ng-select/apes-ng-select.component';
import { KeyCode } from '@shared/apes/ng-select/ng-select.types';
import { ApesModalService } from '@shared/apes/modal';
import { ApesPreviewDialogComponent } from '@shared/ag-grid-ext/upload-component/apes-previewDialog.component';
import { ApesUploadDialogComponent } from '@shared/ag-grid-ext/upload-component';
import { ApesDrawerCustomComponent } from '@shared/ui-zorro';
import { ApesDrawerService } from '@shared/apes/drawer';
import { SearchService } from '@core/services/search.service';
import { ButtonService } from '@core/services/button.service';

@Component({
  selector: 'manual-quotation',
  templateUrl: './manual-quotation.component.html',
  styleUrls: ['./manual-quotation.component.scss'],
})
export class ManualQuotationComponent implements OnInit, AfterViewInit, OnDestroy {

  form = new FormGroup({});
  ctx = { model: {} };
  model: any = {};
  quoteModel: any;
  options: FormlyFormOptions = {};

  expireDate: any;
  expired: boolean = false;
  time: any;
  show: any = '0 小时 0 分钟 0 秒';
  id: any;
  type: any;

  field: FormlyFieldConfig[] = [
    {
      key: 'id',
      type: 'span',
      templateOptions: {
        label: '询价单号',
        divCol: 6,
      },
    },
    {
      key: 'contacts',
      type: 'span',
      templateOptions: {
        label: '联系人',
        divCol: 6,
      },
    },
    {
      key: 'contactPhone',
      type: 'span',
      templateOptions: {
        label: '联系电话',
        divCol: 6,
      },
    },
    {
      key: 'beInvoice',
      type: 'span',
      templateOptions: {
        label: '是否开票',
        divCol: 6,
        valueFormatter: 'value == true ? \'是\' : \'否\'',
      },
    },
    {
      key: 'address',
      type: 'span',
      templateOptions: {
        label: '配送地址',
        divCol: 6,
        showTooltip: true,
        valueFormatter: 'value',
      },
    },
    {
      key: 'vin',
      type: 'span',
      templateOptions: {
        label: '车架号',
        divCol: 6,
      },
    },
    // {
    //   key: 'vehicleConfig',
    //   type: 'span',
    //   templateOptions: {
    //     label: '车型',
    //     divCol: 6,
    //   },
    // },
    {
      key: 'vehicleConfig',
      type: 'drawer',
      templateOptions: {
        label: '车型',
        divCol: 6,
        api: 'sp.enquiryService.queryCustomer',
        formId: 'sp.api.getCustomerCarDetailInfo',
        valueFormatter: 'value.vehicleLabel.name + "/" + value.carModel',
      },
    },
    {
      key: 'createDate',
      type: 'span',
      templateOptions: {
        label: '询价时间',
        divCol: 6,
      },
    },
    {
      key: 'pictures',
      type: 'upload-images',
      hideExpression: '!model.pictures',
      templateOptions: {
        label: null,
        divCol: 12,
        hideLabel: true,
        limit: 2,
        disabled: true,
        customStyle: 'small-picture-card',
      },
    },
  ];

  inquiryPartsList: any[] = [];
  inquiryTyreList: any[] = [];
  inquiryRefitList: any[] = [];

  sourceType: any = 'parts'; // parts:配件   tyre:轮胎

  place: any = '';
  placeOfDispatchItem: any [] = [
    { name: '现货', value: 0 },
    { name: '订货', value: 'n' },
  ];
  antiExplosionItem: any = [
    { name: '是', value: true },
    { name: '否', value: false },
  ];

  warrantyPeriodItem: any[] = [
    { name: '无质保', value: 0 },
    { name: '1个月', value: 1 },
    { name: '3个月', value: 3 },
    { name: '6个月', value: 6 },
    { name: '12个月', value: 12 },
    { name: '24个月', value: 24 },
  ];


  quoteOEApi: any = 'sp.enquiryService.findOE';
  quoteBrandApi: any = 'sp.enquiryService.findBrand';
  quoteTyreBrandApi: any = 'sp.enquiryService.findBrand';

  quoteBranDomain: any = {
    'filters': [
      {
        'field': 'supplierId',
        'operator': 'EQ',
        'value': '{{value}}',
      },
    ],
    'groups': [],
  };

  quoteTyreBranDomain: any = {
    'filters': [
      {
        'field': 'id',
        'operator': 'LIKE',
        'value': '{{value}}',
      },
      {
        'field': 'name',
        'operator': 'LIKE',
        'value': '{{value}}',
      },
    ],
    'groups': [],
    'operator': 'or',
  };

  currentIndex: any = 1;
  partsIndex: any = 1;
  partsSize: any = 5;
  partsTotal: any = 0;

  // @ViewChild('ngSelectRef', { static: false }) ngSelectComponent: ApesNgSelectComponent;

  @ViewChildren('ngSelectRef') ngSelectComponent: QueryList<ApesNgSelectComponent>;

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              protected events: Events,
              private formService: FormService,
              protected route: ActivatedRoute,
              private router: Router,
              private modalService: ApesModalService,
              protected drawerService: ApesDrawerService,
              protected searchService: SearchService,
              private buttonService: ButtonService,
  ) {
  }

  ngOnInit() {
    this.initData();
  }

  ngAfterViewInit() {
  }


  initData() {
    // this.inquiryPartsList = [];
    this.currentIndex = 1;
    this.partsIndex = 1;
    this.partsTotal = 0;
    this.model = {};
    this.place = '';
    this.inquiryPartsList = [];
    this.expireDate = null;
    this.show = '0 小时 0 分钟 0 秒';
    this.id = null;
    this.type = '';
    if (this.time) {
      clearInterval(this.time);
    }

    this.events.subscribe(this.getUrl(), data => {
      let id = data.hasOwnProperty('quoteId') ? data.quoteId : data.id;
      this.quoteModel = data.model;
      if (id == this.id) return;
      let type = data.hasOwnProperty('quoteId') ? 'bjd' : 'xjd';
      this.sourceType = data.type;
      this.getManualQuotationData(id, type, 1);
    });

    if (this.formService.formData.hasOwnProperty('key')) {
      let data = this.formService.formData['key'];
      this.quoteModel = data.model;
      let id = data.hasOwnProperty('quoteId') ? data.quoteId : data.id;
      let type = data.hasOwnProperty('quoteId') ? 'bjd' : 'xjd';
      this.sourceType = data.type;
      this.getManualQuotationData(id, type, this.partsIndex);
      delete this.formService.formData['key'];
    }
  }

  quoteOEDomain(list) {
    let domain = {
      'filters': [
        {
          'field': 'enquiry',
          'operator': '=',
          'value': this.model,
        },
        {
          'field': 'id',
          'operator': '=',
          'value': list['id'],
        },
      ],
      'groups': [],
    };
    return domain;
  }

  checkSubmitQuotationData() {
    for (const resList of this.inquiryPartsList) {
      const hasEmptyField = resList.quoteResult.some((list) => {
        return !this.hasProperty(list, 'systemSign');
      });
      if (hasEmptyField) {
        return false;
      }
    }
    return true;
  }


  changPageIndex(index) {
    if (!this.checkSubmitQuotationData()) {
      this.modalService.confirm({
        apesTitle: '尚有未提交的报价将不会保存，是否切换?',
        apesOkText: '确定切换',
        apesOnOk: () => {
          this.getManualQuotationData(this.id, this.type, index);
        },
        apesCancelText: '继续报价',
        apesOnCancel: () => {
          setTimeout(() => {
            this.partsIndex = this.currentIndex;
          }, 100);
        },
      });
    } else {
      this.getManualQuotationData(this.id, this.type, index);
    }
  }

  getManualQuotationData(id, type, index) {
    this.id = id;
    this.type = type;
    let setData = {
      id: id,
      type: type,
      page: index - 1,
      pages: this.partsSize,
    };
    let api = 'sp.enquiryService.findOneEnquiry';
    this.apiService.post(api, setData).subscribe((res) => {
      console.log('询价单详情--', res);
      this.model = res.enquiry;
      this.place = res.enquiry['place'];
      this.expireDate = res.enquiry['expireDate'];
      if (this.model.hasOwnProperty('type')) {
        this.sourceType = this.model.type;
      }
      // if (this.sourceType == 'parts') {
      //   this.inquiryPartsList = res.enquiryItem;
      // } else if (this.sourceType == 'tyre') {
      //   this.inquiryTyreList = this.filtrationTyreList(res.enquiryItem);
      // }
      switch (this.sourceType) {
        case 'parts':
          this.inquiryPartsList = res.enquiryItem;
          break;
        case 'tyre':
          this.inquiryTyreList = this.filtrationTyreList(res.enquiryItem);
          break;
        case 'refit':
          this.inquiryRefitList = res.enquiryItem;
          break;
      }
      this.partsIndex = res.page + 1;
      this.currentIndex = res.page + 1;
      this.partsTotal = res.size;
      this.setTime();
    });
  }

  setTime() {
    if (this.time) {
      clearInterval(this.time);
    }
    this.showExpireDate();
    this.time = setInterval(() => {
      this.show = this.showExpireDate();
    }, 1000);
  }

  showPhoto(param) {
    // console.log(param);

    let value = deepClone(param.epcPicture);
    if (value) {
      value = replaceAll(value, '\"', '"');
    }
    let dialog: any = ApesPreviewDialogComponent;
    let fileList = JSON.parse(value) || [];
    let option = {
      title: '预览图片',
      _fileList: fileList,
    };

    this.openUploadDialog(option, (result: any) => {
    }, dialog);
  }

  showBadge(param) {
    let num = 0;
    let value = deepClone(param.epcPicture);
    if (value) {
      value = replaceAll(value, '\"', '"');
      num = JSON.parse(value).length;
    }
    return num;
  }

  showDetailed() {
    let api = 'sp.enquiryService.queryCustomer';
    let formId = 'sp.api.getCustomerCarDetailInfo';
    const drawerRef = this.drawerService.create<ApesDrawerCustomComponent, { formId: string, api: string, value: any }, string>({
      apesTitle: '',
      apesContent: ApesDrawerCustomComponent,
      apesWidth: '600px',
      apesContentParams: {
        formId: formId,
        api: api,
        value: this.model,
      },
    });
    drawerRef.afterOpen.subscribe(() => {
      console.log('Drawer(Component) open');
    });

    drawerRef.afterClose.subscribe(data => {
      if (typeof data === 'string') {

      }
    });
  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };
    const openDialog = dialog ? dialog : ApesUploadDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
            // dialogRef.close();
          },
        },
        {
          label: '确定',
          type: 'primary',
          disabled: (componentInstance) => {
            return componentInstance['uploading'];
          },
          onClick: (componentInstance) => {
            // console.log(componentInstance);
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  showExpireDate() {
    let show = ' ';

    // 获取当前日期和时间
    let now = new Date().getTime();

    // 计算倒计时剩余毫秒数
    let distance = this.expireDate - now;

    // 将毫秒数转换为日、时、分、秒
    // let days = Math.floor(distance / (1000 * 60 * 60 * 24));
    let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // 将结果输出到页面上的元素中
    show =
      // days + ' 天 '
      +hours + ' 小时 '
      + minutes + ' 分钟 '
      + seconds + ' 秒 ';

    this.expired = false;
    // 如果倒计时已经结束，则停止计时器
    if (distance < 0) {
      this.expired = true;
      clearInterval(this.time);
      show = '已过期';
      // this.expireCallback();
    }
    return show;
  }

  expireCallback() {
    let setData = {
      id: this.id,
    };
    let api = 'sp.enquiryService.expire';
    this.apiService.post(api, setData).subscribe((res) => {
      // console.log('过时--', res);
    });
  }

  copyOE(value) {
    let textToCopy = value;
    const input = document.createElement('input');
    document.body.appendChild(input);
    input.value = textToCopy;
    input.select();
    document.execCommand('copy');
    this.msg.success('复制成功');
    document.body.removeChild(input);
  }

  checkData(value, param, key) {
    if (key == 'placeOfDispatch') {
      if (value && value >= 0) {
        param[key] = deepClone(value);
      }
    } else {
      param[key] = deepClone(value);
      if (key == 'quoteBrand') {
        this.ngSelectComponent.forEach((selectComponent) => {
          selectComponent.close();
        });
        // this.ngSelectComponent.close();
        if (value.hasOwnProperty('ZBQ')) {
          param['ZBQ'] = value['ZBQ'];
        }
      }
    }
    if (key == 'quoteOE') {
      if (value) {
        param['notTaxUnitPrice'] = deepClone(value['notTaxUnitPrice']);
        param['quoteBrand'] = deepClone(value['spBrand']);
      } else {
        param['notTaxUnitPrice'] = null;
        param['quoteBrand'] = {
          name: '',
          id: '',
        };
      }
    }
  }

  checkTyreData(param, key) {
    let value = deepClone(param[key]);
    param.extend[key] = deepClone(value);
  }

  checkPrice(param) {
    let value = deepClone(param.notTaxUnitPrice);

    if (value && value <= 0) {
      param.notTaxUnitPrice = null;
      this.msg.error('报价不含税不能小于0！！');
    }
  }

  searchData(value, param, key) {
    let data = {};
    if (key == 'quoteOE') {
      data['OE'] = this.filterAlphanumeric(value);
    } else {
      data['name'] = value;
    }
    param[key] = deepClone(data);
  }

  filterAlphanumeric(input) {
    const regex = /[^a-z0-9]/gi;
    return input.replace(regex, '');
  }

  checkTop(value, param) {
    let setData = {
      SpBrand: value,
      category: param,
    };
    let api = 'sp.enquiryService.topOf';
    this.apiService.post(api, setData).subscribe((res) => {
      // console.log('置顶--', res);
      // this.ngSelectComponent.initItemData();
      this.ngSelectComponent.forEach((selectComponent) => {
        selectComponent.initItemData();
      });


      setTimeout(() => {
        // this.ngSelectComponent.getItemData();
        this.ngSelectComponent.forEach((selectComponent) => {
          selectComponent.getItemData();
        });
      }, 100);
    });
  }

  checkPlaceOfDispatch(value, param) {
    if (typeof value == 'object') {
      if (value.value == 'n' || value.value == undefined) return;
      param['placeOfDispatch'] = deepClone(value.value);
    } else {
      if (value) {
        param['placeOfDispatch'] = deepClone(value);
      } else {
        delete param['placeOfDispatch'];
      }
    }
  }

  checkInputNumber(e, param) {
    e.stopPropagation();
    e.preventDefault();
    let num = toNumber((e.target as HTMLInputElement).value);
    let value;
    if (num != 0) {
      value = parseInt(num + '');
    } else {
      value = param['placeOfDispatch'];
    }
    this.checkData(value, param, 'placeOfDispatch');
    // this.checkPlaceOfDispatch(value, param);
  }

  addPartsList(param) {
    // console.log(param);
    let setData = {
      quoteOE: {              //  零件号
        OE: '',
        date: '',
        spBrand: {
          id: '',
          name: '',
        },
      },
      notTaxUnitPrice: null,  // 报价不含税
      ZBQ: null,              // 质保期
      quoteBrand: {           // 品牌
        name: '',
        id: '',
      },
      placeOfDispatch: 0,     // 货源
      note: '',               // 备注
      png: null,              // 图片
    };
    param['quoteResult'].push(setData);
  }

  filtrationTyreList(param) {
    param.forEach((list) => {
      if (list.quoteResult.length != 0) {
        list.quoteResult.forEach((res) => {
          let extend = res.extend;
          res['figure'] = extend['figure'];                 // 花纹
          res['loadIndex'] = extend['loadIndex'];           // 载重指数
          res['speedClass'] = extend['speedClass'];         // 速度等级
          res['antiExplosion'] = extend['antiExplosion'];   // 是否防爆
          res['specification'] = list.oe;                  // 规格尺寸
        });
      }
    });
    return param;
  }

  addTyreList(param) {
    let setData = {
      quoteBrand: {               // 品牌
        name: '',
        id: '',
      },
      extend: {                // 扩展类
        figure: '',            // 花纹
        loadIndex: '',         // 载重指数
        speedClass: '',        // 速度等级
        antiExplosion: false,  // 是否防爆
      },
      figure: '',              // 花纹
      loadIndex: '',           // 载重指数
      speedClass: '',          // 速度等级
      antiExplosion: false,    // 是否防爆
      notTaxUnitPrice: null,   // 报价不含税
      ZBQ: null,               // 质保期
      placeOfDispatch: 0,      // 货源
      note: '',                // 备注
      png: null,               // 图片
      specification: param.oe, // 规格尺寸
    };
    param['quoteResult'].push(setData);
  }

  addStandardTyreList(param) {
    let formId = 'sp.tyre.findByBrandAndFigure';
    let options = {
      multiple: true,
      uniqueKey: 'id',
      addSame: false,
      valueFormatter: 'value.brand + \'/\' + value.figure',
      conditionModel: param,
      title: `选择轮胎规格：${param.oe}`,
    };
    this.searchService.openDialog(formId, options, (result: any) => {
      console.log('标准商品--', result);
      if (result && result.length != 0) {
        result.forEach((res) => {
          let setData = {
            quoteBrand: {                       // 品牌
              name: res.brand,
            },
            extend: {                           // 扩展类
              figure: res.figure,               // 花纹
              loadIndex: res.loadIndex,         // 载重指数
              speedClass: res.speedClass,       // 速度等级
              antiExplosion: res.antiExplosion, // 是否防爆
            },
            figure: res.figure,                 // 花纹
            loadIndex: res.loadIndex,           // 载重指数
            speedClass: res.speedClass,         // 速度等级
            antiExplosion: res.antiExplosion,   // 是否防爆
            notTaxUnitPrice: null,              // 报价不含税
            placeOfDispatch: 0,                 // 货源
            ZBQ: res.ZBQ,                       // 质保期
            note: '',                           // 备注
            png: null,                          // 图片
            specification: res.specification,   // 规格尺寸
            system: true,                       // 标准商品标记
          };
          param['quoteResult'].push(setData);
        });
      }
    }).subscribe();
  }

  addRefitList(param) {
    let formId = 'sp.refit.findByNameAndId';
    let options = {
      multiple: true,
      uniqueKey: 'id',
      addSame: false,
      valueFormatter: 'value.name',
      conditionModel: param,
      title: `选择带安商品：${param.oe}`,
    };
    this.searchService.openDialog(formId, options, (result: any) => {
      console.log('带安商品--', result);
      if (result && result.length != 0) {
        result.forEach((res) => {
          this.checkRefitPrice(param, res);
        });
      }
    }).subscribe();
  }

  checkRefitPrice(model, param) {
    let setData = {
      name: param.name,
    };
    let api = 'sp.spProduct.findProductPrice';
    this.apiService.post(api, setData).subscribe((res) => {
      console.log('带安价格--', res);
      let price = null;
      if (res && res != 0) {
        price = res;
      }
      let resData = {
        quoteOE: {                          // 商品信息
          name: param.name,
          id: param.id,
          category: param.category,
        },
        quoteBrand: {                       // 品牌
          name: param.brand,
        },
        notTaxUnitPrice: price,             // 报价不含税
        placeOfDispatch: 0,                 // 货源
        note: '',                           // 备注
        ZBQ: param.ZBQ,                     // 质保期
        png: null,                          // 图片
        system: true,                       // 标准商品标记
      };
      model['quoteResult'].push(resData);
    });

  }

  removeParts(param, index) {
    param['quoteResult'].splice(index, 1);
  }

  checkSubmitData() {
    let check = true;
    switch (this.sourceType) {
      case 'parts':
        if (this.inquiryPartsList.length == 0) {
          check = false;
        }
        break;
      case 'tyre':
        if (this.inquiryTyreList.length == 0) {
          check = false;
        }
        break;
      case 'refit':
        if (this.inquiryRefitList.length == 0) {
          check = false;
        }
        break;
    }
    return !check;
  }

  submit() {
    // console.log(this.partsIndex);
    // console.log(this.inquiryPartsList);
    // if (this.sourceType == 'parts' && this.inquiryPartsList.length == 0) return;
    // if (this.sourceType == 'tyre' && this.inquiryTyreList.length == 0) return;

    if (this.checkSubmitData()) return;
    if (this.checkQuotationData()) {
      this.submitQuotationData();
    } else {
      this.modalService.confirm({
        apesTitle: '尚有未完整填写零件号、品牌、货源、价格的报价将视为无效报价!',
        apesOkText: '确定提交',
        apesOnOk: () => {
          this.submitQuotationData();
        },
        apesCancelText: '继续报价',
        apesOnCancel: () => {
          setTimeout(() => {
            this.partsIndex = this.currentIndex;
          }, 100);
        },
      });
    }
  }

  submitQuotationData() {
    let num = this.checkDemandData();
    if (num == 0) {
      this.submitData();
    } else {
      this.modalService.confirm({
        apesTitle: `当前页还有${num}个需求未报价，提交后默认视为报价无货！`,
        apesOkText: '确定提交',
        apesOnOk: () => {
          this.submitData();
        },
        apesCancelText: '继续报价',
        apesOnCancel: () => {
          setTimeout(() => {
            this.partsIndex = this.currentIndex;
          }, 100);
        },
      });
    }
  }

  checkQuotationData() {
    if (this.sourceType == 'parts') {
      for (const resList of this.inquiryPartsList) {
        const hasEmptyField = resList.quoteResult.some((list) => {
          return !this.hasProperty(list, 'quoteOE', 'OE')
            || !this.hasProperty(list, 'notTaxUnitPrice')
            || !this.hasProperty(list, 'quoteBrand', 'name')
            || !this.hasProperty(list, 'placeOfDispatch');
        });
        if (hasEmptyField) {
          return false;
        }
      }
    }
    if (this.sourceType == 'tyre') {
      for (const resList of this.inquiryTyreList) {
        const hasEmptyField = resList.quoteResult.some((list) => {
          return !this.hasProperty(list, 'quoteBrand', 'name')
            || !this.hasProperty(list, 'figure')
            || !this.hasProperty(list, 'loadIndex')
            || !this.hasProperty(list, 'speedClass')
            || !this.hasProperty(list, 'antiExplosion')
            || !this.hasProperty(list, 'notTaxUnitPrice')
            || !this.hasProperty(list, 'placeOfDispatch');
        });
        if (hasEmptyField) {
          return false;
        }
      }
    }
    if (this.sourceType == 'refit') {
      for (const resList of this.inquiryRefitList) {
        const hasEmptyField = resList.quoteResult.some((list) => {
          return !this.hasProperty(list, 'quoteOE', 'name')
            || !this.hasProperty(list, 'quoteBrand', 'name')
            || !this.hasProperty(list, 'notTaxUnitPrice')
            || !this.hasProperty(list, 'placeOfDispatch');
        });
        if (hasEmptyField) {
          return false;
        }
      }
    }
    return true;
  }

  checkDemandData() {
    let num = 0;
    if (this.sourceType == 'parts') {
      for (const resList of this.inquiryPartsList) {
        // console.log(resList);
        if (resList.quoteResult.length == 0) {
          num += 1;
        }
      }
    }
    if (this.sourceType == 'tyre') {
      for (const resList of this.inquiryTyreList) {
        // console.log(resList);
        if (resList.quoteResult.length == 0) {
          num += 1;
        }
      }
    }
    return num;
  }

  submitData() {
    let api = 'sp.enquiryService.submit';
    let item = [];
    switch (this.sourceType) {
      case 'parts':
        item = this.inquiryPartsList;
        break;
      case 'tyre':
        item = this.inquiryTyreList;
        break;
      case 'refit':
        item = this.inquiryRefitList;
        break;
    }
    let setData = {
      enquiry: this.model,
      enquiryItem: item,
      sourceType: this.sourceType,
      page: this.currentIndex - 1,
      size: this.partsTotal,
    };
    this.apiService.post(api, setData).subscribe((res) => {
      console.log('提交本页--', res);

      let pages = Math.ceil(this.partsTotal / this.partsSize);

      if (this.currentIndex < pages) {
        let index = this.currentIndex + 1;
        this.getManualQuotationData(this.id, this.type, index);
      } else {
        this.initData();

        this.openLink();
        // let formId = 'form/sp.enquiry';
        // this.router.navigate([formId]);
      }
    });
  }

  openLink() {
    let setData = {
      'id': 'link',
      'action': 'link',
      'option': {
        'id': 'link',
        'name': '询价',
        'data': {
          ...this.quoteModel,
        },
        'api': 'form/sp.enquiry',
        'config': { 'OAInterface': false },
        'ctx': this.ctx,
      },
    };
    this.buttonService.clickButton(setData);
  }


  hasProperty(obj: any, prop: any, subProp?: any) {
    if (subProp) {
      return obj.hasOwnProperty(prop) && (!subProp || obj[prop][subProp] !== '' && obj[prop][subProp] != null);
    } else {
      return obj.hasOwnProperty(prop) && (obj[prop] !== '' && obj[prop] != null);
    }
  }

  private getUrl(): string {
    let url = 'custom/manualQuotation/ManualQuotationComponent';
    // + this.route.snapshot.paramMap.get('formId');
    return url;
  }

  ngOnDestroy() {

    if (this.time) {
      clearInterval(this.time);
    }

    let url = this.getUrl();
    this.events.unsubscribe(url, null);
  }
}

